package nl.maarten.docenthelp.manager;

import java.net.DatagramSocket;
import java.net.Socket;
import java.util.HashMap;

import nl.maarten.docenthelp.entity.Session;
import nl.maarten.docenthelp.util.Util;

public class SessionManager 
{
	private static SessionManager instanceManager;
	
	private HashMap<String, Session> sessions;
	private HashMap<String, Session> closedSessions;
	
	public static SessionManager getInstance()
	{
		if(instanceManager == null)
		{
			instanceManager = new SessionManager();
		}
		
		return instanceManager; 
	}
	private SessionManager()
	{
		sessions = new HashMap<String, Session>();
		closedSessions = new HashMap<String, Session>();
	}
	
	public void clientConnected(Socket socket, DatagramSocket udpSocket)
	{
		for(Session session : sessions.values())
		{
			if (session.getIPAddress().equals(socket.getInetAddress().toString()))
			{
				if(session.getSocket().getPort() == socket.getPort())
				{
					System.out.println( "IP: " + session.getIPAddress() + " on port: " + session.getSocket().getPort() + " already connected!" );
					return;
				}
			}
		}
		
		String ID = Util.MD5(System.currentTimeMillis() + socket.getInetAddress().toString());
		Session session = new Session(ID, socket, udpSocket);
		sessions.put(ID, session);
		
		System.out.println("nieuw client: #" + session.getID() + " at " + session.getIPAddress() + " on port: " + session.getSocket().getPort());
	}
	
	public synchronized HashMap<String, Session> getSessions()
	{
		return sessions;
	}
	
	public synchronized HashMap<String, Session> getClosedSessions()
	{
		return closedSessions;
	}
	
	public void syncSessions()
	{
		for( Session session : getClosedSessions().values() )
		{
			getSessions().remove( session );
		}
	}
}


